package com.terabits.smartriver.service.impl;

import com.terabits.smartriver.mapper.EnterpriseMapper;
import com.terabits.smartriver.mapper.ProjectMapper;
import com.terabits.smartriver.mapper.RegionMapper;
import com.terabits.smartriver.meta.po.Enterprise;
import com.terabits.smartriver.meta.po.Project;
import com.terabits.smartriver.service.EnterpriseService;
import com.terabits.smartriver.util.PageData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;

@Service
@Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class EnterpriseServiceImpl extends BaseService implements EnterpriseService {
    @Autowired
    private EnterpriseMapper enterpriseMapper;
    @Autowired
    private ProjectMapper projectMapper;
    @Resource
    private RegionMapper regionMapper;

    @Override
    public List<PageData> getEnterprise(PageData pageData) {
        String roleProjectNum = String.valueOf(pageData.get("roleProjectNum"));
        if (!StringUtils.isEmpty(roleProjectNum) && !"null".equals(roleProjectNum)) {
            Project project = new Project();
            project.setProjectNum(roleProjectNum);
            List<Project> select = projectMapper.select(project);
            Integer enterpriseId = select.get(0).getEnterpriseId();
            pageData.put("enterpriseId", enterpriseId);
        }
        return enterpriseMapper.selectEnterprise(pageData);
    }

    @Override
    public int addEnterprise(Enterprise enterprise) {

        List enterprises = findObjectsByProperty("enterpriseNum", enterprise.getEnterpriseNum(), enterpriseMapper, Enterprise.class);
        if (enterprises != null && enterprises.size() == 1) {
            return -1;
        }
        return enterpriseMapper.insertSelective(enterprise);
    }

    @Override
    public int updateEnterprise(Enterprise enterprise) {
        return enterpriseMapper.updateByPrimaryKeySelective(enterprise);
    }

    @Override
    public int deleteEnterprise(Integer id) {
        String projectSQL = " SELECT * FROM project WHERE enterprise_id ='" + id + "'";
        List<PageData> projects = regionMapper.selectListSQL(projectSQL);

        if (projects == null || projects.size() == 0) {
            return enterpriseMapper.deleteByPrimaryKey(id);
        }
        return -1;
    }
}
